// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.repo

import android.content.Context
import android.content.res.TypedArray
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.api.ColourV1

@Parcelize
data class Colour(val R: UByte, val G: UByte, val B: UByte): Parcelable {
	constructor(c: ColourV1) : this(c.R, c.G, c.B)

	fun toInt(): Int {
		var rgb = 0xff
		rgb = (rgb shl 8) + R.toInt()
		rgb = (rgb shl 8) + G.toInt()
		rgb = (rgb shl 8) + B.toInt()
		return rgb
	}

	companion object {
		fun fromHex(hex: String?): Colour {
			if (hex == null) return Colour(255u, 255u, 255u)
			return hex.removePrefix("#").let {
				if (it.isEmpty()) {
					Colour(255u, 255u, 255u)
				} else {
					val r = it.substring(0 until 2).toUByte(16)
					val g = it.substring(2 until 4).toUByte(16)
					val b = it.substring(4 until 6).toUByte(16)
					Colour(r, g, b)
				}
			}
		}

		fun getThemeColour(resource: Int, context: Context): Int {
			val a: TypedArray = context.theme.obtainStyledAttributes(
				R.style.Theme_Bimba, intArrayOf(resource)
			)
			val intColor = a.getColor(0, 0)
			a.recycle()
			return intColor
		}
	}
}